﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Collections;

namespace QPEngine
{
    public class UnitySocket
    {
        public Socket mSocket = null;
        public Thread t = null;
        public int idx = -1;
        public string ip = string.Empty;
        public int prot = int.MinValue;
        public string dns = string.Empty;
        public bool isRun = true;

        public UnitySocket(string ip, int prot, int idx)
        {
            this.ip = ip;
            this.dns = ip;
            this.prot = prot;
            this.idx = idx;
        }

        public void SocketConnection(Queue yesip, Queue noip, Action act)
        {
            try
            {
                IPAddress[] ip = Dns.GetHostAddresses(this.ip);
                string newServerIp = "";
                AddressFamily newAddressFamily = AddressFamily.InterNetwork;
                // ylcConst.IPv6Support.getIPType(ip[0].ToString(), this.ip, out newServerIp, out newAddressFamily);
                if (!string.IsNullOrEmpty(newServerIp))
                {
                    this.ip = newServerIp;
                    //Print.LogError(string.Format("{0}:{1}={2}",this.dns,this.prot,this.ip),LogLevel.L1);
                }
                mSocket = new Socket(newAddressFamily, SocketType.Stream, ProtocolType.Tcp);
                //if (AppConst.SocketOutTimer != 0) { mSocket.SendTimeout = AppConst.SocketOutTimer; }

                mSocket.Connect(this.ip, this.prot);

                lock (yesip.SyncRoot) { yesip.Enqueue(this); }
            }
            catch (Exception)
            {
                lock (noip.SyncRoot)
                {
                    if (!noip.Contains(this)) { noip.Enqueue(this); }
                    return;
                }
            }
            act();
        }



        public void close(int closeIndex)
        {
            if (closeIndex == idx && isRun)
            {
                isRun = false;
                if (mSocket == null)
                    return;
                if (mSocket.Connected)
                    mSocket.Close();
            }
            this.mSocket = null;
        }
    }
}
